package com.hj.filter;

import com.alibaba.fastjson.JSONObject;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @author hj
 * @Date 2022/8/16
 * @Description:  这个配合拦截器 获取参数解决request只能读取一次问题
 */

public class HorusRequestWrapper extends HttpServletRequestWrapper  {

    /**
     * 存储body数据的容器
     */
    private final byte[] body;

    public HorusRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        //将body数据存起来
        InputStream is = request.getInputStream();
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        byte[] buff = new byte[1024];
        int len;
        while ((len = is.read(buff)) > 0) {
            bao.write(buff, 0, len);
        }
        body = bao.toByteArray();
    }

    /**
     * 将inputStream里的数据读取出来并转换成json字符串
     *
     * @param in InputStream
     * @return json字符串
     */
    public static String getRequestParams(InputStream in) {
        String params = null;
        BufferedReader streamReader = null;
        try {
            streamReader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
            StringBuilder responseStrBuilder = new StringBuilder();
            String inputStr;
            while ((inputStr = streamReader.readLine()) != null) {
                responseStrBuilder.append(inputStr);
            }
            JSONObject jsonObject = JSONObject.parseObject(responseStrBuilder.toString());
            if (jsonObject == null) {
                return null;
            }
            params = jsonObject.toJSONString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != streamReader) {
                try {
                    streamReader.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return params;
    }

    @Override
    public BufferedReader getReader() {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    @Override
    public ServletInputStream getInputStream() {
        final ByteArrayInputStream inputStream = new ByteArrayInputStream(body);
        return new ServletInputStream() {
            @Override
            public int read() {
                return inputStream.read();
            }

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {
            }
        };
    }


}



